from rest_framework import serializers
from .models import *
from utils.qiniu_tools import ImageHandler
from decimal import Decimal

class CategoryTreeSerializer(serializers.ModelSerializer):
    """
    分类树形结构序列化器（用于前端展示）
    """
    children = serializers.SerializerMethodField()
    display_name = serializers.SerializerMethodField()
    
    class Meta:
        model = Category
        fields = ['id', 'name', 'display_name', 'is_root', 'children']
    
    def get_display_name(self, obj):
        return obj.display_name
    
    def get_children(self, obj):
        if obj.is_root:
            children = Category.objects.filter(parent=obj).order_by('sort_order')
            return CategorySerializer(children, many=True).data
        return []

class CategorySerializer(serializers.ModelSerializer):
    """
    基础分类序列化器
    """
    parent_name = serializers.CharField(source='parent.name', read_only=True)
    display_name = serializers.SerializerMethodField()
    
    class Meta:
        model = Category
        fields = ['id', 'name', 'display_name', 'is_root', 'parent', 'parent_name', 'sort_order']
        extra_kwargs = {
            'parent': {'write_only': True}
        }
    
    def get_display_name(self, obj):
        return obj.display_name
    
    def validate(self, data):
        # 保持你原有的验证逻辑
        if data.get('is_root') and 'parent' in data and data['parent']:
            raise serializers.ValidationError("一级分类不能有父分类")
        if not data.get('is_root') and 'name' in data:
            parent = data.get('parent')
            if parent and Category.objects.filter(
                parent=parent, 
                name=data['name']
        ).exclude(id=self.instance.id if self.instance else None).exists():
                raise serializers.ValidationError("该分类名称已存在")
        return data
class ProductCategoryField(serializers.PrimaryKeyRelatedField):
    """
    专门用于商品创建/更新的分类字段
    自动过滤掉一级分类
    """
    def get_queryset(self):
        return Category.objects.filter(is_root=False)

class ProductImageSerializer(serializers.ModelSerializer):
    url = serializers.SerializerMethodField()

    class Meta:
        model = ProductImage
        fields = ['id', 'image_url', 'display_order', 'url','thumbnail_url']  # 使用模型中的image_url字段
        read_only_fields = ['entire_image_url']
        extra_kwargs = {
            'image_url': {'write_only': True}
        }

    def get_url(self, obj):
        """通过工具类生成访问URL"""
        return obj.entire_image_url
    def get_thumbnail_url(self, obj):
        """获取缩略图URL"""
        return obj.thumbnail_url



class SellerProductSerializer(serializers.ModelSerializer):

    images = ProductImageSerializer(many=True, required=False)
    category = ProductCategoryField()  # 替换原来的category字段
    price = serializers.DecimalField(
        max_digits=10,
        decimal_places=2,
        coerce_to_string=False,  # 确保返回数字而不是字符串
    )
    class Meta:
        model = Product
        fields = [
            'id', 'product_code', 'name', 'description', 
            'price', 'category', 'status', 'delivery_method',
            'delivery_location', 'images', 'created_at','seller'
        ]
        read_only_fields = ['product_code', 'status', 'created_at','seller']
    
class ProductListSerializer(serializers.ModelSerializer):
    images = ProductImageSerializer(many=True, read_only=True)
    seller = serializers.SerializerMethodField()
    class Meta:
        model = Product
        fields = [
            'id', 'name', 'price', 'status', 'product_code',
            'category', 'images', 'created_at','seller'
        ]

    price = serializers.DecimalField(
        max_digits=10,
        decimal_places=2,
        min_value=Decimal('0.00')  # 使用Decimal而不是float
    )
    def get_seller(self, obj):
        """优化卖家信息序列化"""
        if hasattr(obj, 'seller'):
            return {
                'username': obj.seller.username,
                'avatar': obj.seller.avatar_url,
                'credit_score': obj.seller.credit_score
            }


class BuyerProductSerializer(serializers.ModelSerializer):
    images = ProductImageSerializer(many=True, read_only=True)
    seller= serializers.SerializerMethodField()

    class Meta:
        model = Product
        fields = ['id','product_code', 'name', 'price','status', 'category',
                'description', 'images', 'seller', 'delivery_method',
                'delivery_location','created_at']
        price = serializers.DecimalField(
        max_digits=10,
        decimal_places=2,
        min_value=Decimal('0.00')  # 使用Decimal而不是float
        )
        read_only_fields = fields
    
    def get_seller(self, obj):
        """获取卖家基本信息"""
        return {
            'uid': obj.seller.uid,
            'username': obj.seller.username,
            'avatar': obj.seller.avatar_url
        }